﻿using BasicInformation.Domain;
using BasicInformation.Infrastructure.Interface;
using BasicInformation.ReadAPI.Application.Command.LineCommand;
using MediatR;
using Microsoft.EntityFrameworkCore;
using PublicCommon;

namespace BasicInformation.ReadAPI.Application.CommandHandler.LineCommandHandler
{
    public class LineListCommandHandler : IRequestHandler<LineListCommand, PageResult<Line>>
    {
        private readonly ILineRepository lineRepository;

        public LineListCommandHandler(ILineRepository lineRepository)
        {
            this.lineRepository = lineRepository;
        }

        public async Task<PageResult<Line>> Handle(LineListCommand request, CancellationToken cancellationToken)
        {
            var list = lineRepository.GetList().Result.Where(x => !x.IsDel);
            if (!string.IsNullOrEmpty(request.lineName))
            {
                list = list.Where(x => x.LineName.Contains(request.lineName));
            }
            if (!string.IsNullOrEmpty(request.originAddress))
            {
                list = list.Where(x => x.OriginAddress.Contains(request.originAddress));
            }
            if (!string.IsNullOrEmpty(request.endPointAddress))
            {
                list = list.Where(x => x.EndPointAddress.Contains(request.endPointAddress));
            }
            if (request.outOrNot >-1&&request.outOrNot!=0)
            {
                list = list.Where(x => x.OutOrNot == request.outOrNot);
            }
            if (!string.IsNullOrEmpty(request.ownersPhone))
            {
                list = list.Where(x => x.OwnersPhone.Contains(request.ownersPhone));
            }
            if (!string.IsNullOrEmpty(request.ownerUnit))
            {
                list = list.Where(x => x.OwnerUnit.Contains(request.ownerUnit));
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            var pagelist = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            //;
            return new PageResult<Line>
            {
                List = pagelist.ToList(),
                PageCount = pageCount,
                TotalCount = totalCount
            };
        }
    }
}
